<?php
namespace serv\queue\warehouse;

use L;
use of;
use Exception;
use common\commonUpdateTrait;
use common\batchInsert;
use of\base\com\mq;
use Sdk\Plglobal\callPlglobalApiUtil;
use traits\ProductTrait;
use traits\StockTrait;

class plglobal
{
    //同步易达云的库存
    public static function pull($arr)
    {
        try {
            $arr = $arr['data'];
            $warehouseInfo = $arr['warehouse'];
            $action = '/3plapi/openapi/getInventory';
            $method = 'post';
            $page_size = 500;
            $current_page = 1;
            do {
                $data = [
                    'data' => [
                        'warehouseCode' => $arr['warehouse_code'],
                        'pageNum' => $current_page,
                        'pageSize' => $page_size
                    ],
                ];
                //查询库存信息
                $result = callPlglobalApiUtil::callPlglobalApi($action, $method, $data);
                if (!empty($result['data'])) {
                    //只负责取数据，不负责处理
                    $stockArr = $result['data'];
                    $total = $result['total'];
                    $total_page = ceil($total / $page_size);
                    //把查询到的数据交给别一个方法处理
                    foreach ($stockArr as $k => $val) {
                        $key = "check_plglobal_stock_{$val['warehouseCode']}_{$val['systemSku']}";
                        $val = array_merge($val, ['warehouse_id' => $warehouseInfo[$val['warehouseCode']]]);
                        //echo json_encode($val, JSON_UNESCAPED_UNICODE); exit;
                        mq::set(["checkPlglobalStock", $key, $k], $val);
                    }
                } else {
                    $total_page = 1;
                }
                $current_page++;
            } while ($current_page <= $total_page);
            return true;
        } catch (Exception $exp) {
            return false;
        }
    }


    //更新库存或者写入新的库存数据
    public static function check($arr)
    {
        set_time_limit(0);
        try {
            of::work(['warehouse']);
            $val = $arr['data'];
            foreach ($val['customerSkuCode'] as $product_sku) {
                $sql = "SELECT stock_id, sku FROM stock WHERE 1 
                    AND warehouse_id = '{$val['warehouse_id']}' 
                    AND sku_code = '{$product_sku}';";
                $result = L::sql($sql, 'warehouse');
                if (!empty($result)) {
                    //更新数据
                    $data = [
                        'sku' => StockTrait::tran2sku($product_sku),
                        'available_stock' => $val['availableStockQty'], //可用
                        'lock_stock' => $val['inUsedStockQty'], //锁
                        'stock' => $val['availableStockQty'] + $val['inUsedStockQty'], //在库
                        'on_way_stock' => $val['transferOnWayStockQty'], //调拔在途
                        'status' => StockTrait::stockStatus($product_sku),
                        'belong' => of::config('env.PUBLIC_BELONG'),
                        'updated_by' => of::config('env.SYSTEM_ID'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ];
                    //更新
                    commonUpdateTrait::update('stock', $data, $result[0]['stock_id'], 'stock_id');
                } else {
                    //插入数据
                    $position = self::position($val['warehouse_id']);
                    $sku = StockTrait::tran2sku($product_sku);
                    $skuInfo = ProductTrait::skuInfo($sku);
                    $data[] = [
                        'position_id' => !empty($position) ? $position['position_id'] : 1,
                        'area_id' => !empty($position) ? $position['area_id'] : 1,
                        'warehouse_id' => $val['warehouse_id'],
                        'sku' => $sku,
                        'sku_code' => $product_sku,
                        'sku_name' => !empty($skuInfo) ? $skuInfo['sku_name'] : '',
                        'sku_name_en' => !empty($skuInfo) ? $skuInfo['sku_name_en'] : '',
                        'stock' => $val['availableStockQty'] + $val['inUsedStockQty'],
                        'available_stock' => $val['availableStockQty'],
                        'lock_stock' => $val['inUsedStockQty'],
                        'on_way_stock' =>  $val['transferOnWayStockQty'], //调拔在途
                        'status' => StockTrait::stockStatus($product_sku),
                        'belong' => of::config('env.PUBLIC_BELONG'),
                        'created_by' => of::config('env.SYSTEM_ID'),
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_by' => of::config('env.SYSTEM_ID'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ];
                    $sql = batchInsert::insert('stock', $data);
                    L::sql($sql, 'warehouse');
                }
            }
            of::work(true);
            return true;
        } catch (Exception $exp) {
            of::work($exp);
            return false;
        }
    }

    //获取此仓库默认库位
    private static function position($warehouse_id)
    {
        $sql = "SELECT position_id, area_id FROM `position` WHERE 1 AND warehouse_id = '{$warehouse_id}';";
        $rows = L::sql($sql, 'warehouse');
        return (!empty($rows)) ? $rows[0] : [];
    }
}